<template>
  <div class="main">
    <topbar_back back-url="index" back-content="返回"
                 center-content="上传加分项证明" content-color="black" is-show-center="true"></topbar_back>
    <div class="middle">
      <div class="name">
        <span class="text">加分项名称</span>
        <input class="input" v-model="actName" autocomplete="off" maxlength="100" >
        <span class="example_tip">例：档案馆助理实践证明</span>
      </div>
      <div class="tip">
        <span class="text">备注（50字以内）</span>
        <textarea class="input" v-model="actTip" maxlength="50"></textarea>
      </div>
    </div>
    <div class="bottom">
      <div class="upload_wrap">
        <div class="touchfield" v-show="uploadedexceljson === null">
          <div class="center">
            <div class="x"></div>
            <div class="y"></div>
          </div>
          <span class="text">{{buttoncontent}}</span>
          <input type="file" @change="upload()"
                 ref="inputer" class="fileinput"/>
        </div>
        <img class="img" :src="uploadImg">
      </div>
      <div class="tip">
        <span class="text">
          {{tipcontent}}
        </span>
      </div>
        <div class="button_wrap" @click="submit()">
           <span class="text">确认提交</span>
        </div>
    </div>
    <tip_nochoose :tipfile="tipfile"
                  v-if="isShowFinishedTip"
                  @closetip="closeFinishedTip($event)"></tip_nochoose>
  </div>
</template>

<script>
import tipNoChoose from '../../components/public/tip_nochoose'
import topbarBack from '../../components/public/topbar_back'
import uploadImageImg from '../../assets/img/icon/upload_image.svg'
import uploadExcelImg from '../../assets/img/icon/upload_excel.svg'
// 引入证明端的业务层
import certificationServices from '../../service/certification'
export default {
  name: 'UploadProve',
  data () {
    return {
      uploadImageImg: uploadImageImg,
      uploadExcelImg: uploadExcelImg,
      uploadImg: null,
      buttoncontent: '',
      tipcontent: '',
      backUrl: '',
      type: '',
      clickedSubmit: false,
      actName: '',
      actTip: '',
      uploadedexceljson: null,
      isShowFinishedTip: false,
      tipfile: [{
        title: 'Excel提交完毕',
        content: ''
      }]
    }
  },
  components: {
    topbar_back: topbarBack,
    tip_nochoose: tipNoChoose
  },
  methods: {
    showFinishedTip () {
      this.isShowFinishedTip = true
    },
    closeFinishedTip () {
      this.isShowFinishedTip = false
    },
    // 检验json
    checkExcelJson (json) {
      if (json[0].studentId !== '学号' || json[0].name !== '姓名' ||
        json[0].college !== '学院') {
        alert('您上传的excel不规范，第2行不规范，请严格按照样表填写')
        return false
      }
      const regex = /^[0-9]*$/
      for (let i = 1; i < json.length; i++) {
        if (!regex.test(json[i].studentId)) {
          // 如果有学号不是整数，那么excel有问题
          alert('您上传的excel第' + (i + 2) + '行不规范')
          return false
        }
      }
      return true
    },
    tranExcelToJson (file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader()
        // 箭头函数的写法，this指向vm实例，箭头函数内的this，就是箭头函数被定义时所在作用域的this
        // reader.onload = (e) => {
        // 匿名函数的写法，this指向fileReader，函数内的this，就是调用函数的那个对象
        // 即let reader = new FileReader()中的reader，reader.onload中的reader
        reader.onload = function (e) {
          // 在index.html中引入了CDN，在vue.config.js中设置了'xlsx': 'xlsx'，所以可以直接使用
          // await this.tranExcelToJson(e)
          let wb = XLSX.read(e.target.result, {
            type: 'binary'
          })
          // wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
          // wb.Sheets[Sheet名]获取第一个Sheet的数据
          // 如果用的是箭头函数，this应该仍然为vm，可以直接赋值给data()中的变量
          // this.uploadedexceljson = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]))
          let data1 = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]))
          resolve({
            // promise结束，返回data
            data: data1
          })
        }
        // readAsBinaryString是异步的，一般程序会直接执行到这里然后不等待onload执行完成就直接跳出去
        // 但是因为加了promise，在本函数里面的所有流程都执行完以后才会返回promise
        // 所以，在onload处理完成后才结束promise
        // 这样就不会因为readAsBinaryString异步而导致函数提前结束
        reader.readAsBinaryString(file)
      })
    },
    async uploadexcel () {
      // 上传excel的时候调用此方法
      let inputDOM = this.$refs.inputer
      // 通过DOM取文件数据
      if (!inputDOM.files) {
        return
      }
      let file = inputDOM.files[0]
      const extention2 = file.name.split('.')[1] === 'xlsx'
      if (!extention2) {
        alert('请上传新版本Excel的xlsx文件')
        return
      }
      let result = await this.tranExcelToJson(file)
      let json = JSON.parse(result.data)
      // console.log('tranExcelToJson执行完毕')
      console.log('处理完的data为' + json)
      if (this.checkExcelJson(json) === true) {
        this.uploadedexceljson = json
      }
    },
    upload () {
      // alert('上交材料！')
      if (this.type === 'excel') {
        this.uploadexcel()
        // alert('Excel提交完毕')
        this.showFinishedTip()
      }
    },
    async submit () {
      // 验证输入的内容是不是为空
      if (this.actName === '' || this.actTip === '' || this.uploadedexceljson === null) {
        alert('请将信息填写完毕！')
        return
      }
      // 如果输入合法，判断有没有重复提交
      if (this.clickedSubmit === true) {
        // 如果已经点击过，证明提交正在进行，直接返回，不进行任何操作
        return
      } else {
        // 如果没有点击过，开始进行提交
        this.clickedSubmit = true
      }
      // alert('确认提交！')
      let data = {
        name: 'tip_operation',
        params: {
          tiptitle: 'title',
          leftcontent: '继续上传',
          lefturl: 'uploadprove',
          lefturltype: this.$route.params.type,
          rightcontent: '查看已上传',
          righturl: 'file',
          // righturltype: 'submited',
          righturltype: 'unsubmited',
          footChoose: 'index'
        }
      }
      // 在这里把数据提交给后端
      if (this.type === 'excel') {
        // 如果是提交excel的话，执行提交excel的操作
        let uploaderId = this.$store.getters.getLoginUser.userid // 从登录的用户处获取上传者的易班ID
        let organization = this.$store.getters.getLoginUser.organization // 从登录的用户处获取上传者的组织
        // 从excel表格里面获取学生信息
        // 把excel的表头姓名、学号、学院 去掉
        this.uploadedexceljson.shift()
        let result = await certificationServices.uploadCertification(uploaderId,
          organization, this.actName, this.actTip, this.uploadedexceljson)
        result = result.data
        if (result.code === this.$global.OK) {
          data.params.tiptitle = '上传成功!'
        } else if (result === this.$global.FAILED) {
          data.params.tiptitle = '上传失败'
        }
      } else {
        // 如果type === 'image'，执行提交图片的操作，自行补充
      }
      // 点击设为false，以便下一次进行提交
      this.clickedSubmit = false
      // 页面跳转--加入history，使用router.replace()不加入history
      this.$router.push(data)
    }
  },
  mounted () {
    if (this.$route.params.type === 'excel') {
      this.uploadImg = this.uploadExcelImg
      this.buttoncontent = '点击上传Excel'
      this.tipcontent = '备注：仅支持excel表格形式的文件，同时需要按照样表规范填写，若填写不规范将退回'
      this.type = 'excel'
    } else if (this.$route.params.type === 'image') {
      this.uploadImg = this.uploadImageImg
      this.buttoncontent = '点击上传图片'
      this.tipcontent = '备注：请上传证明材料，并确保材料清晰度高，以便后续材料审核'
      this.type = 'image'
    }
  }
}
</script>

<style lang="scss" scoped>
.main{
  width: 100%;
  height: 100%;
  background-color: $background-color;
  @mixin text_tip{
    height: px2rem(17);
    line-height:px2rem(17);
    font-size: $text-size-small;
    color: #666666;
  }
  .fileinput{
    width: 200px;
    height: 200px;
    border: 2px solid red;
    opacity: 0.5;
  }
  .middle{
    @mixin text_title{
      height: px2rem(25);
      line-height:px2rem(25);
      font-size: $text-size-imp;
      font-weight: bold;
      color: #666666;
    }
    @mixin text_input{
      border-radius: px2rem(4);
      border: 0;
      background-color: #FFF;
      color: $text-color;
      font-size: $text-size-normal;
    }
    .name{
      width: 80%;
      height: px2rem(89);
      margin: px2rem(22) auto 0;
      /*border: px2rem(1) solid red;*/
      .text{
        @include text_title
      }
      .input{
        @include text_input;
        width: calc(100% - #{px2rem(8)});
        height: px2rem(36);
        line-height: px2rem(36);
        margin: px2rem(6) 0 px2rem(5) 0;
        padding: 0 px2rem(8);
      }
      .example_tip{
        @include text_tip;
      }
    }
    .tip{
      width: 80%;
      height: px2rem(139);
      margin: px2rem(20) auto 0;
      /*border: px2rem(2) solid red;*/
      .text {
        @include text_title
      }
      .input {
        @include text_input;
        width: calc(100% - #{px2rem(8)});
        height: px2rem(108);
        margin: px2rem(6) 0 0 0;
        padding: 0 px2rem(8);
        line-height: px2rem(25);
      }
    }
  }
  .bottom{
    .upload_wrap{
      background-color: #DBDBDB;
      width: 80%;
      height: px2rem(108);
      margin: px2rem(34) auto 0;
      border-radius: px2rem(4);
      text-align: center;
      position: relative;
      border: px2rem(1) solid transparent;
      .img {
        width: px2rem(105);
        height: px2rem(89);
        position: absolute;
        top: px2rem(9);
        left: 45%;
        z-index: 1;
      }
      .touchfield{
        width: px2rem(105);
        height: px2rem(75);
        /*border: px2rem(2) solid red;*/
        margin: px2rem(21) auto 0;
        position: relative;
        z-index: 2;
        .center {
          width: px2rem(46);
          height: px2rem(46);
          /*border: px2rem(2) solid red;*/
          margin: 0 auto px2rem(7);
          position: relative;
          @mixin xy{
            border-radius: px2rem(2);
            position: absolute;
            background-color: #666666;
          }
          .x {
            @include xy;
            width: px2rem(46);
            height: px2rem(4);
            top: px2rem(21);
            left: 0;
          }
          .y {
            @include xy;
            width: px2rem(4);
            height: px2rem(46);
            top: 0;
            left: px2rem(21);
          }
        }
        .text{
          height: px2rem(20);
          line-height: px2rem(20);
          font-size: px2rem(14);
          font-weight: bold;
          color: #666666;
        }
        .fileinput{
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          /*border: 2px solid black;*/
          opacity: 0;
        }
      }

    }
    .tip{
      margin: px2rem(5) auto 0;
      width: 80%;
      .text{
        @include text_tip;
      }
    }
    .button_wrap {
      width: 80%;
      height: px2rem(44);
      margin: px2rem(20) auto 0;
      border-radius: px2rem(24);
      background: -webkit-linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* Safari 5.1 - 6.0 */
      background: -o-linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* Opera 11.1 - 12.0 */
      background: -moz-linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* Firefox 3.6 - 15 */
      background: linear-gradient(to right,$gradients-color-lightblue, $ui-color-assist-purple); /* 标准的语法 */
      text-align: center;
      .text{
        line-height: px2rem(44);
        font-size: $text-size-imp;
        color: #FFF;
        margin: 0 auto;
        /*border: px2rem(2) solid red;*/
      }
    }
  }
}
</style>
